import { CloseCircleOutlined } from '@ant-design/icons';
import { Button, Input, Table } from "antd";
import { useEffect, useReducer } from "react";

export default function SearchTable({ columns, onLoad, onSelect, onSelectEnd, placeholder }) {
  const [state, dispatch] = useReducer((state, action) => {
    switch (action.type) {
      case 'loading':
        return { ...state, loading: true };
      case 'loaded':
        return {
          ...state,
          loading: false,
          data: action.data,
          pagination: {
            ...state.pagination,
            total: action.total,
            current: Math.min(Math.floor(action.total / state.pagination.pageSize) + 1, state.pagination.current),
          },
        };
      case 'change':
        return {
          ...state,
          q: action.q == null ? state.q : action.q,
          pagination: action.pagination || state.pagination,
          sorter: action.sorter || state.sorter,
        };
      case 'select':
        return { ...state, selected: action.selected };
      default:
        return state;
    }
  }, {
    loading: true,
    q: '',
    sorter: [],
    pagination: {
      showTotal: total => `共${total}条`,
      showSizeChanger: true,
      total: 0,
      pageSize: 10,
      current: 1,
    },
    data: [],
    selected: undefined,
  });

  useEffect(() => {
    onLoad(state.q, state.sorter, state.pagination.current, state.pagination.pageSize).then(({ Total, Rows }) => {
      dispatch({ type: 'loaded', total: Total, data: Rows });
    });
    // eslint-disable-next-line
  }, [state.q, state.sorter, state.pagination.current, state.pagination.pageSize]);

  useEffect(() => {
    onSelect(state.selected);
    // eslint-disable-next-line
  }, [state.selected]);

  return (
    <>
      <div style={{ display: 'flex', paddingBottom: 10 }}>
        <Button onClick={() => onSelectEnd()}><CloseCircleOutlined />清空</Button>
        <div style={{ flex: 1 }}></div>
        <Input.Search placeholder={placeholder} onSearch={q => dispatch({ type: 'change', q })} style={{ width: 200 }} />
      </div>
      <Table rowKey="ID" size="small" loading={state.loading} pagination={state.pagination} showSorterTooltip={false}
        columns={columns} dataSource={state.data}
        onChange={(pagination, filters, sorter) => dispatch({ type: 'change', pagination, filters, sorter })}
        rowSelection={{
          hideSelectAll: true,
          selectedRowKeys: state.selected ? [state.selected.ID] : [],
          onSelect: (record) => dispatch({ type: 'select', selected: record }),
        }}
        onRow={(record) => ({
          onClick: () => dispatch({ type: 'select', selected: record }),
          onDoubleClick: () => onSelectEnd(record),
        })}
      />
    </>
  );
}